import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import { getApiConfig, discoverWorkingServer, testServerConnection, getFunctionServer } from '../config';

interface NetworkStatusProps {
  onServerChange?: (serverUrl: string) => void;
}

const NetworkStatus: React.FC<NetworkStatusProps> = ({ onServerChange }) => {
  const [currentServer, setCurrentServer] = useState<string>('');
  const [isConnected, setIsConnected] = useState<boolean>(false);
  const [isTesting, setIsTesting] = useState<boolean>(false);
  const [functionServers, setFunctionServers] = useState<{[key: string]: string}>({});

  useEffect(() => {
    checkCurrentStatus();
    loadFunctionServers();
  }, []);

  const loadFunctionServers = () => {
    const servers = {
      '认证服务': getFunctionServer('auth'),
      '文件上传': getFunctionServer('upload'),
      '通用API': getFunctionServer('api'),
    };
    setFunctionServers(servers);
  };

  const checkCurrentStatus = async () => {
    const config = getApiConfig();
    setCurrentServer(config.baseURL);
    
    try {
      const connected = await testServerConnection(config.baseURL);
      setIsConnected(connected);
    } catch (error) {
      setIsConnected(false);
    }
  };

  const testConnection = async () => {
    setIsTesting(true);
    try {
      const config = getApiConfig();
      const connected = await testServerConnection(config.baseURL);
      setIsConnected(connected);
      
      if (connected) {
        Alert.alert('连接成功', `服务器 ${config.baseURL} 连接正常`);
      } else {
        Alert.alert('连接失败', `服务器 ${config.baseURL} 无法连接`);
      }
    } catch (error) {
      Alert.alert('测试失败', '网络测试过程中发生错误');
    } finally {
      setIsTesting(false);
    }
  };

  const findWorkingServer = async () => {
    setIsTesting(true);
    try {
      const workingServer = await discoverWorkingServer();
      if (workingServer) {
        setCurrentServer(workingServer);
        setIsConnected(true);
        onServerChange?.(workingServer);
        Alert.alert('发现可用服务器', `已切换到: ${workingServer}`);
      } else {
        Alert.alert('无可用服务器', '所有配置的服务器都无法连接');
      }
    } catch (error) {
      Alert.alert('服务器发现失败', '自动发现服务器时发生错误');
    } finally {
      setIsTesting(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>网络状态监控</Text>
      
      <View style={styles.statusRow}>
        <Text style={styles.label}>主服务器状态:</Text>
        <View style={[styles.statusIndicator, { backgroundColor: isConnected ? '#34C759' : '#FF3B30' }]} />
        <Text style={[styles.statusText, { color: isConnected ? '#34C759' : '#FF3B30' }]}>
          {isConnected ? '已连接' : '未连接'}
        </Text>
      </View>
      
      <View style={styles.serverRow}>
        <Text style={styles.label}>主服务器:</Text>
        <Text style={styles.serverUrl} numberOfLines={1}>
          {currentServer}
        </Text>
      </View>
      
      {/* 功能专用服务器状态 */}
      <View style={styles.functionServers}>
        <Text style={styles.sectionTitle}>功能专用服务器:</Text>
        {Object.entries(functionServers).map(([name, url]) => (
          <View key={name} style={styles.functionServerRow}>
            <Text style={styles.functionName}>{name}:</Text>
            <Text style={styles.functionUrl} numberOfLines={1}>
              {url}
            </Text>
          </View>
        ))}
      </View>
      
      <View style={styles.buttonRow}>
        <TouchableOpacity 
          style={[styles.button, styles.testButton]} 
          onPress={testConnection}
          disabled={isTesting}
        >
          <Text style={styles.buttonText}>
            {isTesting ? '测试中...' : '测试连接'}
          </Text>
        </TouchableOpacity>
        
        <TouchableOpacity 
          style={[styles.button, styles.discoverButton]} 
          onPress={findWorkingServer}
          disabled={isTesting}
        >
          <Text style={styles.buttonText}>
            {isTesting ? '发现中...' : '自动发现'}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#f8f9fa',
    padding: 16,
    borderRadius: 8,
    marginVertical: 8,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 16,
  },
  statusRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  label: {
    fontSize: 14,
    fontWeight: '600',
    color: '#333',
    marginRight: 8,
  },
  statusIndicator: {
    width: 12,
    height: 12,
    borderRadius: 6,
    marginRight: 8,
  },
  statusText: {
    fontSize: 14,
    fontWeight: '600',
  },
  serverRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  serverUrl: {
    fontSize: 12,
    color: '#666',
    flex: 1,
    marginLeft: 8,
    fontFamily: 'monospace',
  },
  functionServers: {
    marginBottom: 16,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#555',
    marginBottom: 8,
  },
  functionServerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 4,
  },
  functionName: {
    fontSize: 14,
    fontWeight: '600',
    color: '#444',
    marginRight: 8,
  },
  functionUrl: {
    fontSize: 12,
    color: '#666',
    flex: 1,
    fontFamily: 'monospace',
  },
  buttonRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  button: {
    flex: 1,
    paddingVertical: 8,
    paddingHorizontal: 16,
    borderRadius: 6,
    marginHorizontal: 4,
  },
  testButton: {
    backgroundColor: '#007AFF',
  },
  discoverButton: {
    backgroundColor: '#34C759',
  },
  buttonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
    textAlign: 'center',
  },
});

export default NetworkStatus; 